package com.itheima.d2_reflect_test;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;

/*
    对象框架
    目标：保存任意对象的字段和其数据到文件中去
 */
public class ObjectFrame {
    public static void saveObject(Object obj) throws IOException, IllegalAccessException {
        // 1. 创建字节类对象
        final Class clz = obj.getClass();

        // 2. 获取所有成员变量
        final Field[] declaredFields = clz.getDeclaredFields();

        // 3. 所有成员变量写入文件
        final PrintWriter pw = new PrintWriter(new FileWriter("object.txt", true));

        pw.println("===================="+clz.getSimpleName()+"=====================");
        for (Field declaredField : declaredFields) {
            // 暴力反射
            declaredField.setAccessible(true);
            final Object filedValue = declaredField.get(obj);
            pw.println(declaredField.getName() + "=" + filedValue);
        }

        // 4. 关闭流
        pw.flush();
        pw.close();
    }
}
